package com.learn.algorithm;

/**
 *算法-二分法
 */
public class BinarySearch {
    /**
     * 以int数组为例
     * @param data 数据
     * @param aim  aim为需要查找的数
     * @return
     */
    public int binarySearch(int[] data,int aim) {
        int start = 0;
        int end = data.length -1;
        int mid = ( start + end ) / 2;

        //如果data[mid]等于aim则死循环，所以排除
        int i = 0;
        while( data[mid] != aim && end > start) {
            System.out.println("--------------------------------"+i);
            System.out.println("mid："+mid);
            if ( data[mid] > aim ) {
                end = mid - 1;
                System.out.println("end："+end);
            } else if ( data[mid] < aim ) {
                start = mid + 1;
                System.out.println("start："+start);
            }
            mid = ( start + end ) / 2;
            System.out.println("mid："+mid);
            i++;
        }

        return data[mid] != aim ? -1 : mid;
    }

    public static void main(String[] args) {
        BinarySearch binarySearch = new BinarySearch();

        int[] data = {1,2,3,4,5,6,7,8,9,10,11,12,13};
        int key =  2;

        System.out.println(binarySearch.binarySearch(data,key));

    }
}
